/*
    Project:        Home Power Control
    File:           HPCWindVane.cpp
    Author:         christian@karunamusic.at
    Date:           02.2015
    Description:    Sensor to measure the direction of the wind.
                    The sensor works with 8 reed-switches connected to different resistors.
                    The magnet can close 2 switches so that we have 16 positions.
                    The output of the voltage-divider is measured via MCP3008 (A2D).
 */

#include <QStringList>
#include <unistd.h>
#include <limits>
#include <iostream>
#include <linux/spi/spidev.h>
#include <wiringPi.h>
#include <Logger/HPCLogger.h>
#include "HPCWindVane.h"

HPCWindVane::HPCWindVane( const QString& name, quint32 id, quint8 channel, quint8 pin )
    : HPCSensor( TSensorType::HPCWindVane,name,id,pin ), m_Channel(channel)
{
    QString dev = "/dev/spidev0." + QString::number(m_Channel);
    m_A2D = new HPCMCP3008( dev, SPI_MODE_0, 1000000, 8 );
}

HPCWindVane::~HPCWindVane()
{
    delete m_A2D;
}

QString HPCWindVane::asString() const
{
    QString ret = HPCSensor::asString();

    ret += ", channel " + QString::number(m_Channel);
    return ret;
}

void HPCWindVane::Measure()
{
    int i;
    int volt;
    unsigned char data[3];
    static int dirVolt[] = { 210, 270, 300, 410, 600, 790, 930,1310,1490,1930,2030,2260,2530,2670,2860,3050 };
    static unsigned int dirs[] = {6,4,5,8,7,10,9,2,3,12,11,16,1,14,15,13};
    HPCValue res;

    data[0] = 1;
    data[1] = (m_Pin + 8) << 4;
    data[2] = 0;

    m_A2D->spiWriteRead( data, sizeof(data) );

    volt = ((((data[1] & 3) << 8) + data[2]) * 3300) / 1024;

    for ( i = 0; i < 16; i++ )
    {
        if ( volt <= dirVolt[i] )
            break;
    }

    if ( i >= 16 )
    {
        res.V() = (unsigned int)0;
    }
    else
    {
        res.V() = dirs[i];
    }

    LOG( trace, Name() << ": measured value: " << res.V().toUInt() );
    m_Value = res;
}
